package com.hopscotch.service.impl;

import com.hopscotch.mapper.UserDetailsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    //数据层查数据库的对象
    @Autowired
    private UserDetailsMapper userDetailsMapper;
    //重写该方法
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.hopscotch.entity.User sysUser = userDetailsMapper.userDetailLogin(username);
        if (sysUser == null){
            throw new UsernameNotFoundException("用户不存在");
        }

        //Set<String> userDetailsAuth = userDetailsMapper.userDetailsAuth(sysUser.getId());
        //将String集合转化为GrantedAuthority集合
        Set<GrantedAuthority> authSet = new HashSet<>();
        authSet.add(new SimpleGrantedAuthority("1"));
        /*userDetailsAuth.forEach(auth -> {
            authSet.add(new SimpleGrantedAuthority(auth));
        });*/

        return new User(username,sysUser.getUserPassword(),authSet);
    }
}
